package com.uwantsoft.business.infrastructure.repository.querier;

import com.uwantsoft.business.facade.dto.user.DriverOverviewQueryCondition;
import com.uwantsoft.business.service.domain.user.Driver;
import com.uwantsoft.util.paging.AbstractQuerier;
import com.uwantsoft.util.paging.ParameterFilter;
import org.hibernate.Query;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.util.StringUtils;

/**
 * @author Chuanbao
 */
public class DriverOverviewQuerier extends AbstractQuerier<Driver> {
    private DriverOverviewQueryCondition condition;

    public DriverOverviewQuerier(HibernateTemplate hibernateTemplate, DriverOverviewQueryCondition condition) {
        super(hibernateTemplate);
        this.condition = condition;
        addUsernameFilter();
    }

    private void addUsernameFilter(){
        if(StringUtils.hasText(condition.getUsername())){
            addFilter(new ParameterFilter() {
                @Override
                public void setParameter(Query query) {
                    query.setParameter("username","%"+condition.getUsername()+"%");
                }

                @Override
                public String getSubHql() {
                    return " and d.username like :username";
                }
            });
        }
    }

    @Override
    public int getStartPosition() {
        return condition.getStartIndex();
    }

    @Override
    public int getItemsAmountPerPage() {
        return condition.getObjectsPerPage();
    }

    @Override
    public String getResultHql() {
        return "from Driver d where 1=1 " + getSubHql();
    }

    @Override
    public String getAmountHql() {
        return "select count(*) from Driver d where 1=1" + getSubHql();
    }
}
